package com.blog.config;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义网关全局Filters
 */
@Configuration
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    /**类似于javaWeb的doFilter,但是
     *  exchange,封装了request和response
     *  注:基于webflux模型,所以是ServerHttpRequest.而不是HttpServletRequest
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //相当于httpRequest对象
        ServerHttpRequest request = exchange.getRequest();
        //相当于httpResponse对象
        ServerHttpResponse response = exchange.getResponse();
        System.out.println("经过全局Filters处理");
        Mono<Void> filter = chain.filter(exchange);
        System.out.println("响应回来的Filters处理");
        return filter;
    }

    //多个Filters的执行顺序,数字越小越先执行
    //特殊:-1,在所有Filters之前执行(包含内置Filters)
    //如果多个自定义Filters都是-1则结果随机
    @Override
    public int getOrder() {
        return -1;
    }

}
